//
//  Data.swift
//  CooperSwift
//
//  Created by 计海峰 on 2021/4/26.
//  Copyright © 2021 CooperSwift. All rights reserved.
//

import Foundation

public extension Data {
    
    var bytes: [UInt8] {
        // http://stackoverflow.com/questions/38097710/swift-3-changes-for-getbytes-method
        return [UInt8](self)
    }
    
    func string(encoding: String.Encoding) -> String? {
        return String(data: self, encoding: encoding)
    }
    
    static func jsonToData(jsonDic: Dictionary<String, Any>) -> Data? {
        if (!JSONSerialization.isValidJSONObject(jsonDic)) {
            debugPrint("is not a valid json object")
            return nil
        }
        //利用自带的json库转换成Data
        //如果设置options为JSONSerialization.WritingOptions.prettyPrinted，则打印格式更好阅读
        let data = try? JSONSerialization.data(withJSONObject: jsonDic, options: [])
//        //Data转换成String打印输出
//        let str = String(data:data!, encoding: String.Encoding.utf8)
//        //输出json字符串
//        print("Json Str:\(str!)")
        return data
    }
    
    func dataToDictionary(data:Data) ->Dictionary<String, Any>?{
        do{
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            let dic = json as! Dictionary<String, Any>
            return dic
        }catch _ {
            debugPrint("失败")
            return nil
        }
    }

    
}
